package com.qq.open.weibo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.StringBody;

import com.qq.open.common.OpenQqConstants;
import com.qq.open.common.OpenQqUtils;
import com.qq.open.common.json.JSONException;
import com.qq.open.common.json.JSONObject;
import com.qq.open.weibo.bean.param.WeiBoDelIdolParamBean;
import com.qq.open.weibo.bean.result.WeiBoDelIdolResultBean;


/**
 * 
 * 取消收听腾讯微博上的用户
 * 
 * @author HaoLiang
 *
 */
public class WeiBoDelIdol {
	/** QQ互联工具类 */
	private OpenQqUtils oqu = new OpenQqUtils();
	
	
	/**
	 * 收听腾讯微博上的用户
	 * 
	 * @param paramBean 参数
	 * @return 接口返回数据
	 * @throws JSONException 
	 * @throws IOException 
	 * @throws  
	 */
	public WeiBoDelIdolResultBean delIdol(WeiBoDelIdolParamBean paramBean) throws JSONException, IOException {
		
		// 获取接口返回的数据
		String jsonData = oqu.doPost(OpenQqConstants.WEIBO_DEL_IDOL_URL, this.getInterfaceParam(paramBean));
		
		return this.jsonToBean(jsonData);
	}
	
	/**
	 * 获取接口地址
	 * 
	 * @param paramBean 参数
	 * @return 接口地址
	 * @throws UnsupportedEncodingException 
	 */
	private MultipartEntity getInterfaceParam(WeiBoDelIdolParamBean paramBean) throws UnsupportedEncodingException {
		MultipartEntity reqEntity = new MultipartEntity();
		
		// AccessToken
		reqEntity.addPart("access_token", new StringBody(paramBean
				.getAccessToken()));

		// AppId
		reqEntity.addPart("oauth_consumer_key", new StringBody(oqu.getConfigValue("qq.appid")));

		// Openid
		reqEntity.addPart("openid", new StringBody(paramBean.getOpenId()));

		// 定义API返回的数据格式
		reqEntity.addPart("format", new StringBody("json"));
		
		// 要收听的用户的账户名列表
		if (oqu.isNotNull(paramBean.getName())) {
			reqEntity.addPart("name", new StringBody(paramBean.getName(), Charset.forName("UTF-8")));
		}
		
		// 要收听的用户的openid列表
		if (oqu.isNotNull(paramBean.getFopenIds())) {
			reqEntity.addPart("fopenids", new StringBody(paramBean.getFopenIds()));
		}
		
		return reqEntity;
	}
	

	
	/**
	 * json数据转换成Bean数据
	 * 
	 * @param paramBean 
	 * @return
	 * @throws JSONException 
	 */
	private WeiBoDelIdolResultBean jsonToBean(String jsonData) throws JSONException {
		
		WeiBoDelIdolResultBean resultBean = new WeiBoDelIdolResultBean();
		
		JSONObject jsonObjRoot = new JSONObject(jsonData);
		
		// 接口返回错误的场合
		if (jsonObjRoot.getInt("ret") != 0) {
			// 设置错误标识为真
			resultBean.setErrorFlg(true);
			// 设置错误编号
			resultBean.setErrorCode(jsonObjRoot.get("errcode").toString());
			// 设置错误内容
			resultBean.setErrorMes(jsonObjRoot.getString("msg"));
		} 
		
		return resultBean;
	}
}
